/**
 * Project Name:jrx
 * File Name:DateUtils.java
 * Package Name:cn.bluemobi.queue.util
 * Date:2015年8月27日下午4:40:56
 * Copyright (c) 2015, bluemobi.cn All Rights Reserved.
 *
 */

package cn.bluemobi.platform.utils;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

/**
 * Description: <br/>
 * Date: 2015年8月27日 下午4:40:56 <br/>
 * 
 * @author hut
 * @version
 * @see
 */
public class DateUtils {
    protected static final Logger log = LogManager.getLogger(DateUtils.class);

    public static String format(Timestamp time, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(new Date(time.getTime()));
    }

    public static String format(Date time, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(time);
    }

    /**
     * 时间差 Description: <br/>
     * 
     * @author lvxh
     * @param startTime
     * @param endTime
     * @param format
     * @param timeDiffType(0:天,1:小时,2:分钟,3:秒)
     * @return
     */
    public static long timeDiff(String startTime, String endTime, String format, Integer timeDiffType) {
        long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
        long nh = 1000 * 60 * 60;// 一小时的毫秒数
        long nm = 1000 * 60;// 一分钟的毫秒数
        long ns = 1000;// 一秒钟的毫秒数
        long diff;

        long result = 0;
        try {
            SimpleDateFormat sd = new SimpleDateFormat(format);
            // 获得两个时间的毫秒时间差异
            diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
            long day = diff / nd;// 计算差多少天
            long hour = diff / nh;// 计算差多少小时
            long min = diff / nm;// 计算差多少分钟
            long sec = diff / ns;// 计算差多少秒
            if (timeDiffType == 0) {
                log.info("天:" + day);
                result = day;
            }
            if (timeDiffType == 1) {
                log.info("小时:" + hour);
                result = hour;
            }
            if (timeDiffType == 2) {
                log.info("分钟:" + min);
                result = min;
            }
            if (timeDiffType == 3) {
                log.info("秒:" + sec);
                result = sec;
            }
            // 输出结果
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
